﻿#include "GLLInc.h"
#include "GLLObjAnim.h"
#include "GLLLvlObj.h"
#include "GLLObjSpcl.h"

namespace GLL
{
	//-----------------------------------------------------------------------------
	//Skeleton Animation

	const String OCSkltnAnmtn::name("SkltnAnmtn");

	OCSkltnAnmtn::OCSkltnAnmtn() :ObjectComponent(name)
	{
		_loop = true;
		_rate = 1.0f;

#ifdef GLL_OGRE
		_skel = 0;
		_as = 0;
#endif
	}

	void OCSkltnAnmtn::ApplyAnim()
	{
#ifdef GLL_OGRE
		if(_as) _as->setEnabled(false);
		ObjectMesh* pOM = (ObjectMesh*)_obj;
		_as = pOM->_entity->getAnimationState(_name);
		_as->setEnabled(true);
#endif
	}

	void OCSkltnAnmtn::AnimAddTime( TimeMS ms )
	{
#ifdef GLL_OGRE
		if(!_as) return;
		float tslf = (float)ms;
		tslf *= _rate;
		_as->addTime(tslf / 1000.0f);
#endif
	}

	bool OCSkltnAnmtn::Ok2Add( Object* p)
	{
		ObjectMesh* pOM = dynamic_cast<ObjectMesh*>(p);
		if(pOM) return true;
		return false;
	}

	void OCSkltnAnmtn::ApplyChange()
	{
		if(_animChgd){
			ApplyAnim();
		}

		if(_as){
			if(_propChgd){
				_as->setLoop(_loop);
			}
		}
	}

	void OCSkltnAnmtn::Update( TimeMS ms)
	{
		ApplyChange();
		ChangeBoneScale();
		AnimAddTime(ms);
	}

	//-----------------------------------------------------------------------------

	void OCSkltnAnmtn::ObjectLoaded()
	{
		ObjectMesh* pOM = dynamic_cast<ObjectMesh*>(_obj);
		Ogre::Entity* pEnt = pOM->_entity;
		_skel = pEnt->getSkeleton();

		Ogre::Skeleton::BoneIterator iter = _skel->getBoneIterator();

		while(iter.hasMoreElements())
		{
			Ogre::Bone* b = iter.getNext();
			b->setInheritScale(false);
		}
	}

	void OCSkltnAnmtn::ScaleBone(const String& bone_name, float scale)
	{
		_bone = bone_name;
		_scale = scale;
		_scaleChgd.Set();
	}

	void OCSkltnAnmtn::ChangeBoneScale()
	{
		if(!_skel) return;

		ObjectMesh* pOM = dynamic_cast<ObjectMesh*>(_obj);
		Ogre::Entity* pEnt = pOM->_entity;
		Ogre::SubEntity* pse = pEnt->getSubEntity(0);

		pse->setCustomParameter(1, Ogre::Vector4(0, 0, 1, 0));

		if(!_scaleChgd) return;

		Ogre::Bone* b = _skel->getBone(_bone);
		if(!b){
			SS ss; ss << "no bone named:" << _bone << "object:"<<_obj->StrID();
			GLL_Throw( ss );
		}

		b->setScale(_scale, _scale, _scale);
		b->setManuallyControlled(true);
		OCSkltnAnmtn* pocsa = (OCSkltnAnmtn*)_obj->GetCom(OCSkltnAnmtn::name);
		Ogre::Animation* pA = _skel->getAnimation(pocsa->_name);
		//pA->destroyNodeTrack(b->getHandle());
		//Ogre::NodeAnimationTrack* pnat = pA->createNodeTrack(b->getHandle());

		//pocsa->_as->setTimePosition(0);
	}

};//GLL

